<?php

/**
 * Admin
 *
 * Description: Class for User Management Module
 *
 * PHP Version: 1.2.3
 *
 * @author Johari <joharijumali@gmail.com>
 */

/**
 * Admin
 *
 * Description: Class for User Management Module
 *
 * @author Johari <joharijumali@gmail.com>
 */

class Administrator_User_Controller extends Base_Controller
{

    public $restful = true;

	/**
     * Function post_search
	 *
	 * @return post_search.
     */
    public function post_list()
	{

        $input = Input::get();

        if (Input::has('searchval')) {
            return json_encode(Console_User::userSearchList($input));
        } else {
            return json_encode(Console_User::listUser());
        }
    }

	/**
     * Function get_list
	 *
	 * @return get_list.
     */
    public function get_list()
	{

        $input = Input::get();

        if (Input::has('searchval')) {
            $data['userlist'] = Console_User::userSearchList($input);
        } else {
            $data['userlist'] = Console_User::listUser();
        }

        $data['allgroup'] = Data_Attendance_Group::arrayGroup();
        $data['allrole'] = Console_Role::arrayRoles();
        $data['alldept'] = Data_Department_Department::arrayDept();
        $data['division'] = array('Sila Pilih');
        $data['unit'] = array('Sila Pilih');
        $data['supervisorone'] = array('Sila Pilih');
        $data['supervisortwo'] = array('Sila Pilih');

    	return View::make('administrator.user.list', $data);
    }
	 
	/**
     * User Registration function
     * Component : register
     * Method 	 : ajax post
	 *
	 * @return void.
     */
    public function post_register()
    {
        $input = Input::all();

        $input['key'] = $key = Str::random(32, 'alpha');
		
        $validation = Console_User::validate($input);
        $validateProfile = Console_Profile::validate($input);

        if ($validateProfile->fails()) {
            return json_encode($validateProfile->errors);
        } elseif ($validation->fails()) {
            return json_encode($validation->errors);
        }
		
        $resgisteredUser = Console_User::registerUser($input);

        if ($resgisteredUser) {
            try {
                $mailer = Message::to($input['sup_emel']);
                $mailer->from("itbmwebtas@gmail.com", __('global.sysname'));
                $mailer->subject(Str::title(__('admin.subjectconfirm')));
                $mailer->body('view: admin::plugin.email');
                $mailer->body->username = $input['su_username'];
                $mailer->body->name = $input['sup_nama'];
                $mailer->body->password = $input['su_password'];
                $mailer->body->key = $key;
                $mailer->html(true);
                $mailer->send();

                Log::write('email', 'Message was to '.$input['sup_emel'].' was sent.');
            } catch (Exception $e) {
                Log::write('email', 'Message was to '.$input['sup_emel'].' not sent.');
                Log::write('email', 'Mailer error: '.$e->getMessage());
            }

            return json_encode(Console_User::listUser());
        }
    }
	 
	/**
     * Retrieve User Information function
     * Component : userinfo
     * Method 	 : ajax post
	 *
	 * @return get_userinfo.
     */
    public function get_userinfo()
    {
        $input = Input::all();
        $profile = Console_User::userinfo($input['id']);
        return json_encode($profile);
    }
	 
	/**
     * Retrieve User Information function
     * Component : userinfo
     * Method 	 : ajax post
	 *
	 * @return get_supervisor.
     */
    /*public function get_supervisor()
    {
        $jabatan = Input::get('jabatan');
        $bahagian = (Input::get('bahagian'))?Input::get('bahagian'):0;
        $unit = (Input::get('unit'))?Input::get('unit'):0;
        $exclude = (Input::get('exclude'))?Input::get('exclude'):0;
		
        $profile = Console_Profile::listSupervisor($jabatan, $bahagian, $unit, $exclude);
        return json_encode($profile);
    }*/

    public function get_supervisorOne()
    {
        $jabatan = Input::get('jabatan');
        $bahagian = (Input::get('bahagian'))?Input::get('bahagian'):0;
        $unit = (Input::get('unit'))?Input::get('unit'):0;
		
        $profile = Console_Profile::listSupervisorOne($jabatan, $bahagian, $unit);
        return json_encode($profile);
    }
	
	public function get_supervisorTwo()
    {
        $jabatan = Input::get('jabatan');
		
        $profile = Console_Profile::listSupervisorTwo($jabatan);
        return json_encode($profile);
    }
	 
	/**
     * Retrieve User Division / Unit Base on Dept function
     * Component : userinfo
     * Method 	 : ajax post
	 *
	 * @return get_divlist.
     */
    public function get_divlist()
	{
        $listDiv = Data_Department_Division::arrayDiv(Input::get('id'));

        return json_encode($listDiv);
    }
	
	/**
     * Function get_unitlist
	 *
	 * @return get_unitlist.
     */
    public function get_unitlist()
	{
        $listUnit = Data_Department_Unit::arrayUnit(Input::get('dept'), Input::get('div'));

        return json_encode($listUnit);
    }
	
	/**
     * Update User Information function
     * Component : userinfo
     * Method 	 : ajax post
	 *
	 * @return post_updateUser.
     */
    public function post_updateUser()
	{
        $input = Input::all();

        $rules = array(
                'sup_nama' => 'required',
                'sur_id' => 'required|not_in:0',
                'sup_no_ic' => 'required|unique:sys_user_profile,sup_no_ic,'.$input['su_id'].',su_id',
                'wp_tarikh_mula' => 'required',
                'sup_emel' => 'required|email|unique:sys_user_profile,sup_emel,'.$input['su_id'].',su_id',
                'sup_id_pengguna' => 'required|max:11|unique:sys_user_profile,sup_id_pengguna,'.$input['su_id'].',su_id'
                //'sup_id_pengguna' => 'required|integer|unique:sys_user_profile,sup_no_ic,'.$input['su_id'].',su_id'
        );

        $validation = Validator::make($input, $rules);

        if ($validation->fails()) {
            return json_encode($validation->errors);
        }

        $input['su_password'] = Str::random(16, "alpha");
        $input['key'] = $key = Str::random(32, 'alpha');

        $status = Console_User::updateUser($input);

		if ($status == 4 || $status == 'Baru') {
            try {
                $mailer = Message::to($input['sup_emel']);
                $mailer->from('admin@3fresorces.com', __('global.sysname'));
                $mailer->subject(Str::title(__('admin.subjectconfirm')));
                $mailer->body('view: admin::plugin.email');
                $mailer->body->username = $input['sup_emel'];
                $mailer->body->name = $input['sup_nama'];
                $mailer->body->password = $input['su_password'];
                $mailer->body->key = $key;
                $mailer->html(true);
                $mailer->send();

                Log::write('email', 'Message to '.$input['sup_emel'].' was sent.');
            } catch (Exception $e) {
                Log::write('email', 'Message to '.$input['sup_emel'].' not sent.');
                Log::write('email', 'Mailer error: '.$e->getMessage());
            }			
		}

        return json_encode(Console_User::listUser());
    }
	
	/**
     * Function post_deleteAccount
	 *
	 * @return post_deleteAccount.
     */
    public function post_deleteAccount()
	{
        $id = Input::get('id');

        $existed = Console_User::find($id);

        $ic = $existed->profile->sup_no_ic;
				
		$bil = Attendance_Attend::where('su_id', '=', $id)->count();
		
        if ($existed->su_status === 'Pengesahan' OR $bil === 0) {
            $existed->delete();
            $existed->profile->delete();
            Log::write('User', 'Delete Account '.$ic.' By <code>'.Auth::user()->su_username.'</code>');
            return json_encode(Console_User::listUser());
        } else { 
            return json_encode(array('fail'=>'Pengguna ini sedang diguna oleh sistem'));
        }
    }
	
	/**
     * User Reset login function
     * Component : resetlogin
     * Method 	 : ajax post
	 *
	 * @return void.
     */
    public function post_resetlogin()
	{
        $validatekey = Str::random(32, 'alpha');

        $input = Input::all();
        $pword = Str::random(16, 'alpha');

        $user = Console_User::find($input['id']);

        $user->su_password = $pword;
        $user->su_status = 3;
        $user->su_validationkey = $validatekey;
        $user->save();

        Log::write('User', 'Reset Login User '.$user->profile->sup_no_ic.' By <code>'.Auth::user()->su_username.'</code>');

        try {
            $mailer = Message::to($user->profile->sup_emel);
            $mailer->from('admin@3fresources.com', __('global.sysname'));
            $mailer->subject(Str::title(__('admin.subjectreset')));
            $mailer->body('view: admin::plugin.emailAccReset');
            $mailer->body->username = $user->profile->sup_emel;
            $mailer->body->name =$user->profile->sup_nama;
            $mailer->body->password = $pword;
            $mailer->body->key = $validatekey;
            $mailer->html(true);
            $mailer->send();
        } catch (Exception $e) {
            Log::write('email', 'Message was to '.$user->profile->sup_emel.' not sent.');
            Log::write('email', 'Mailer error: '.$e->getMessage());
        }

        return Console_User::listUser();
    }
	 
	/**
     * User Reset password function
     * Component : resetpassword
     * Method 	 : ajax post
	 *
	 * @return void.
     */
    public function post_resetpassword()
	{
        $input = Input::all();

        $rules = array(
                'oldpassword' => 'required',
                'password' => 'required|between:6,12',
                'repassword' => 'required|same:password'
        );

        $validation = Validator::make($input, $rules);

        if ($validation->fails()) {
            return json_encode($validation->errors);
        }

        $user = Console_User::find(Auth::user()->su_id);
		
        if (Hash::check($input['oldpassword'], $user->su_password) && $input['password'] == $input['repassword']) {
            $user->su_password = Hash::make($input['password']);
            $user->save();

            Log::write('User', 'Reset Password User '.$user->profile->sup_no_ic.' By <code>'.Auth::user()->su_username.'</code>');
        
            return true;
        }
    }
	
	/**
     * User Profile function
     * Component : profile
     * Method 	 : ajax post
	 *
	 * @return void.
     */
    public function get_profile()
    {
        $profile = Console_Profile::loggedprofile();

        return $profile;
    }
	
	/**
     * Function post_profile
	 *
	 * @return post_profile.
     */
    public function post_profile()
    {
        $input = Input::all();


        $profile = Console_Profile::find(Auth::user()->su_id);

        $profile->sup_nama = $data['sup_nama'];
        $profile->sup_no_ic = $data['sup_no_ic'];
        $profile->sup_no_pekerja = $data['sup_no_pekerja'];
        $profile->sup_emel = $data['sup_emel'];
        $profile->wp_tel = $data['sup_tel'];
        $profile->sup_tarikh_mula = date('m-d-Y', strtotime($data['wp_tarikh_mula']));
        $profile->sup_tarikh_tamat = isset($data['wp_tarikh_tamat'])?date('m-d-Y', strtotime($data['wp_tarikh_tamat'])):'';
        $profile->sukp_no_auto = $data['wjkp_no_auto'];
        $profile->suj_no_auto = $data['wpj_no_auto'];
        $profile->sub_no_auto = $data['wpb_no_auto'];
        $profile->suu_no_auto = $data['wpu_no_auto'];
        $profile->sur_id = $data['sur_id'];
        $profile->su_status = $data['su_status'];
        $profile->sup_penyelia_satu = $data['sup_penyelia_satu'];
        $profile->sup_penyelia_dua = $data['sup_penyelia_dua'];
        $profile->sup_tidak_kelihatan = $data['sup_tidak_kelihatan'];

        $profile->save();

        Log::write('User', 'Update Profile User '.$profile->sup_no_ic);

        $profile = Console_Profile::loggedprofile();

        return $profile;
    }

}

?>